<?php


/**************************************/
//  modified at: 28Aug2007
//  author: francissem@gmail.com
/**************************************/


/*
pathjoin("file","product","apple.jpg") //out file/product/apple.jpg
pathjoin("/file/","/product/","///apple.jpg") //out /file/product/apple.jpg
*/
function pathjoin(){
    $args=func_get_args();
	$is_http=preg_match("/^http:\/\//i",$args[0]);
	$prehtml="";
	if($is_http)$args[0]=preg_replace("/^http:\/\//i","/",$args[0]);
	if($is_http) $prehtml="http:/";
	return $prehtml.ereg_replace("(/+)","/",implode("/",$args));
}

/*
quote(array(17,67,34)) //out '17','67','34'
*/


//see php.net
if(!function_exists('http_build_query')) {
   function http_build_query( $formdata, $numeric_prefix = null, $key = null ) {
       $res = array();
       foreach ((array)$formdata as $k=>$v) {
           $tmp_key = urlencode(is_int($k) ? $numeric_prefix.$k : $k);
           if ($key) {
               $tmp_key = $key.'['.$tmp_key.']';
           }
           if ( is_array($v) || is_object($v) ) {
               $res[] = http_build_query($v, null, $tmp_key);
           } else {
               $res[] = $tmp_key."=".urlencode($v);
           }
       }
       return implode("&", $res);
   }
}

if(!function_exists('file_put_contents')){
	function file_put_contents($filename,$data) {
	  $f=fopen($filename,"w");
	  if (!$f) {
	    return false;
	  } else {
	    fwrite($f,$data);
	    fclose($f);
	    return true;
	  }
	}
}

/*
	echo $_SERVER['QUERY_STRING'] //out abc=0&efg=test&hij=hello
	query_update("abc=1") //out abc=1&efg=test&hij=hello
	query_update("abc=1","hij") //out abc=1&hij=hello
*/
function query_update($keys,$onlykeys=NULL){
	$qs=array();
	parse_str($_SERVER['QUERY_STRING'],$qs);
	if(is_array($keys)) $arr=$keys;
	if(is_string($keys)) {
		$arr=array();
		parse_str($keys,$arr);
	}
	if(is_string($onlykeys)){
		$onlykeys=explode(",",$onlykeys);
	}
	if($onlykeys!=NULL) {
		$tmpqs=array();
		foreach($qs as $k=>$v){
			if(in_array($k,$onlykeys))$tmpqs[$k]=$v;
		};
		$qs=$tmpqs;
	}
	if(isset($arr)) foreach($arr as $k=>$v){
		$qs[$k]=$v;
	}
	
	return http_build_query($qs);
}







//see php.net
if(!function_exists('json_encode')) {
	function json_encode($meta){
		require_once("JSON.php");
		$json = new Services_JSON();
		return $json->encode($meta);
	}
}
//see php.net
if(!function_exists('json_encode')) {
	function json_decode($meta){
		require_once("JSON.php");
		$json = new Services_JSON();
		return $json->decode($meta);
	}
}

function isEmail($email){
	return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}


/**
 * 
 * 
 * 
 * @uses 	link(":add") //for action or view
 * 			
 * 			<form action="<?=link(":save")?>">...</form> //for action
 * 			
 * 			<a href="<?=link(":view")?>"></a>
 * 
 * 			link("/admin/product/category/:add","id=1")
 * 
 * 			
 * 			
 *
 * */
function linkto($rel,$query=null){
	global $__is_start_view;
	
	if(is_string($query)){
		parse_str($query,$query_array);
	}else{
		$query_array=$query;
	}
	if(isset($_GET["lang"])) $query_array["lang"]=trim($_GET["lang"]);
	//var_dump($query_array);
	$paths = explode(":",$rel);
	
	$urlpath = $paths[0];
	$type = $paths[1];
	
	if(substr($urlpath,0,1)=="/"){
		//abs path
		$link = pathjoin(BASE,$urlpath);
	}else{
		//rel path
		$link = pathjoin(dirname($_SERVER['SCRIPT_NAME']),$urlpath);
		
	}
	
	$basename = basename($link);
	if(in_array(strpos($basename,'.'),array(-1,""))){
		$link = pathjoin($link,basename($_SERVER['SCRIPT_NAME']));
	}
	
	$query=http_build_query($query_array);
	
	if(isset($type)) $link=pathjoin($link,$type);
	if(isset($query)) $query="?$query";
	
	if($__is_start_view){
		return htmlspecialchars($link.$query);
	}else{
		return $link.$query;
	}
}



$__canRedirect=false;
function redirect($url){
	/*global $__canRedirect;
	if($__canRedirect){*/
	
		header("Location: {$url}");
		echo "<SCRIPT>window.location.href='{$url}'</SCRIPT>";
		exit;
	//}
}

function file_ext($file){
	$names = explode(".","$file");
	return end($names);
}



/**
 * array_read
 *
 * @param array $arr, path $path
 * @return mix
 * 
 * @example 
 * $arr = array("record"=>array(array("name"=>"apple"),array("name"=>"orange")));
 * echo array_read($arr,"record[0][name]"); // out apple
 */
function array_read($arr,$path){
//	$path = ereg_replace("(\[|\])","",$path);

	$str = @ereg_replace("(|\]\[|)",",",$path);
	
	$querystrs = array_slice(split("\[|\]\[|\]",$path),1,-1);
	
	$curnodes[]=$arr;
	$nxtnodes=array();
	$selected_value=array();
	$level=0;
	
	
	while(count($curnodes)>0 && count($querystrs)>$level){
		
		
		$nodes=array_shift($curnodes);	

		if(is_array($nodes)){
			$parts = explode("=>",$querystrs[$level]);
			$keyquery = $parts[0];
			$valuequery = $parts[1];
			if(empty($valuequery))$valuequery="*";
			
			if($level==count($querystrs)-1){
				//select
				
				if(isset($nodes[$keyquery])) {
					
					$selected_value[]=$nodes[$keyquery];
				}
				
			}else{
				//next node
				
				if(isset($nodes[$keyquery])) {
					$nxtnodes[]=$nodes[$keyquery];
				}
				else{
					if($keyquery=="*" && $valuequery=="*"){
						$nxtnodes=array_merge($nxtnodes,$nodes);
					}else{
						$keynodes = array();
						if($keyquery=="*"){
							$keynodes=$nodes;
						}
						$keycons=array();
						if(ereg("([0-9]*)-([0-9]*)",$keyquery,$keycons)){
							foreach(range($keycons[1],$keycons[2]) as $ind){
								$keynodes[]=$nodes[$ind];
							}
						}
						
						
						if($valuequery=="*"){
							$nxtnodes=array_merge($nxtnodes,$keynodes);
						}							
						
						//var_dump(split(,$valuequery));
						
						
						$connodes=array();
						$cons = array();
						if(ereg("([a-zA-Z0-9_]*) *(=|>|<|>=|<=|in) *([a-zA-Z0-9_|() ]*)",$valuequery,$cons)){
							
							if($cons[2]==">") {
								foreach($keynodes as $k=>$n) {
									if(empty($connodes[$k])) $connodes[$k]=1;
									$connodes[$k]&=($n[$cons[1]]>$cons[3]);
								}
							}
							if($cons[2]=="<") {
								foreach($keynodes as $k=>$n) {
									if(empty($connodes[$k])) $connodes[$k]=1;
									$connodes[$k]&=($n[$cons[1]]<$cons[3]);
								}
							}
							if($cons[2]=="=") {
								foreach($keynodes as $k=>$n) {
									$connodes[$k]&=($n[$cons[1]]==$cons[3]);
								}
							}
							if($cons[2]==">=") {
								foreach($keynodes as $k=>$n) {
									if(empty($connodes[$k])) $connodes[$k]=1;
									$connodes[$k]&=($n[$cons[1]]>=$cons[3]);
								}
							}
							if($cons[2]=="<=") {
								foreach($keynodes as $k=>$n) {
									if(empty($connodes[$k])) $connodes[$k]=1;
									$connodes[$k]&=($n[$cons[1]]<=$cons[3]);
								}
							}
							if($cons[2]=="in") {
								if(empty($connodes[$k])) $connodes[$k]=1;
								$c3=array();
								if(ereg("^\(([0-9a-zA-Z_| ]*)\)",$cons[3],$c3)){
									$connodes[$k]&=(in_array($n[$cons[1]],explode("|",$c3[1])));
									foreach($keynodes as $k=>$n) {
										if(empty($connodes[$k])) $connodes[$k]=1;
										$connodes[$k]&=in_array($n[$cons[1]],explode("|",$c3[1]))==1;
									}
								}
							}
						}
						
						foreach($connodes as $k=>$c){
							if($c==1) $nxtnodes[]=$keynodes[$k];
						}
						
						//foreach($keynodes as $kn){
						
						
						//foreach($nodes as $n) $nxtnodes[]=$n;
							
					}
				}
			}
			
		}
		
		
		
		if(count($curnodes)==0) {
			$curnodes=$nxtnodes;
			$nxtnodes=array();
			$level++;
		}
		
	};
	
	if(count($selected_value)==0) return null;
	return $selected_value;
}


function array_readone($arr,$path){
	$rarr = array_read($arr,$path);
	if($rarr==null) return $rarr;
	return $rarr[0];
}
	
	
function array_select($selectkeys,$arr){
	$rarr=array();
	if(is_string($selectkeys)) $selectkeys = explode(",",$selectkeys);
	foreach((array_intersect(array_keys($arr),$selectkeys)) as $k) $rarr[$k]=$arr[$k];
	return $rarr;
}

function array_nlist($key,$arr){
	$rarr=array();
	if(is_array($arr)){
		foreach($arr as $v)$rarr[]=$v[$key];
	}
	return $rarr;
}


function camelize($name){
	$parts = explode("_",$name);
	foreach($parts as $i=>$p)  $parts[$i] = ucfirst($p);
	return implode($parts);
}

function quote($mix){
	if(is_array($mix)){
		$arr=$mix;
	}else{
		$arr=array($mix);
	}
	
	$warr=array();
	foreach($arr as $item){
		if(is_string($item)){
			$item = addslashes($item);
			$warr[]="'{$item}'";
		}else{
			$warr[]=$item;
		}
	}
	return implode(",",$warr);
	
}

function mod($name,$params=NULL){
	return Model::From($name,$params);
}

function expr($expr){
	return new SqlExpr($expr);
}

function e($htmlent){
	return htmlentities($htmlent,ENT_COMPAT,"UTF-8");
}

function array_combine($a1,$a2){
	for($i=0;$i<count($a1);$i++)
	    $ra[$a1[$i]] = $a2[$i];
	if(isset($ra)) return $ra; else return false;
}

function isBlank($str){
	if($str==NULL) return true;
	$str=trim($str);
	return empty($str);
}


function cutstr($str,$len){
	if(strlen($str)>$len){
		return substr($str,0,$len)."...";
	}else{
		return $str;
	}
}


function valueAsKey($key,$arr){
	$rarr=array();
	foreach($arr as $v){
		$rarr[$v[$key]]=$v;
	}
	return $rarr;
}

function manyValueInKey($key,$arr){
	$rarr=array();
	foreach($arr as $v){
		if(!isset($rarr[$v[$key]])){
			$rarr[$v[$key]]=array();
		}
		$rarr[$v[$key]][]=$v;
	}
	return $rarr;
}

function actionpath(){
	if(!empty($_SERVER['PATH_INFO'])){
		return "/";
	}else{
		return $_SERVER['PATH_INFO'];
	}
}
function gencode($len=50){
	$chars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPGRSTUVWXYZ";
	$r="";
	foreach(range(0,$len) as $t){
		$r.=$chars[rand(0,strlen($chars))];
	}
	return uniqid($r);
}
function getlang(){
	$lang_mod = mod("Language",array($_GET["lang"]));
	
	return $lang_mod->current();
}

function file_put_contents($n,$d) {
  $f=@fopen($n,"w");
  if (!$f) {
    return false;
  } else {
    fwrite($f,$d);
    fclose($f);
    return true;
  }
}

function conf_dump(){
	global $_conf;
	$c = $_conf;
	unset($c["db"]);
	var_dump($c);
}

function lang_show($word){
	global $__view;
	if(getlang()!=DEF_LANG){
		$text = $__view->_lang[$word];
		if(empty($text)) return $word;
		echo  $text;
		return false;
	}
	return true;
}

function urlbase(){
	if($GLOBALS["system"]["has_lang_request"] || $GLOBALS["system"]["lang"]!=DEF_LANG){
		return  BASE."/{$GLOBALS["system"]["lang"]}";
	}else{
		return  BASE;
	}
}

function getsys($name){
	return $GLOBALS["system"][$name];
}

function getconf($name){
	return $GLOBALS["_conf"][$name];
}


function sql_dump($return=false){
	return print_r(SqlProfile::Dump(),$return);
}

function trace($msg){
	$logfile = pathjoin(ROOT,"log/log.txt");
		
	if ($handle = fopen($logfile, 'a+')) {
		
		fwrite($handle, date("Y-m-d H:i:s")."\n");
		fwrite($handle, html_entity_decode($msg)."\n\n");
		
		fclose($handle);
	}
}

function gmtime($timezone_min=0){
	static $gs;
	if(!isset($gs)){
		$d = date("O");
		$gs = intval(substr($d,0,1).(substr($d,1,2)*3600)+(substr($d,3,2)*60));
	}
	return time()-$gs+($timezone_min*60);
}

function serverdate($time){
	if(!ereg("^[0-9]*$",$time)) $time = strtotime($time);
	return date(getconf("date_format"),$time+intval(getconf("timezone"))*60);
}

function qupdate($keys,$query=null){
   return updateq($keys,$query);
} 

function updateq($keys,$query=null){
    if($query==null)$_SERVER['QUERY_STRING'];
    if(is_string($keys)) parse_str($keys,$keys);
    if(is_string($query)) parse_str($query,$query);
    return http_build_query(array_merge($query,$keys));
} 

function is_deflang(){
	return getsys("lang")==DEF_LANG;
}


function nl2li($text){
	$arr = explode("\n",$text);
	$html="";
	foreach($arr as $row)$html.="<li>$row</li>\n";
	return $html;
}

function wrap_http_link($text){
   $text = ereg_replace("[a-zA-Z]+://([-]*[.]?[a-zA-Z0-9_/-?&%])*", "<a href=\"\\0\">\\0</a>", $text);
   $text = ereg_replace("(^| )(www([-]*[.]?[a-zA-Z0-9_/-?&%])*)", "\\1<a href=\"http://\\2\">\\2</a>", $text);
   return $text;
}

function wrap_email_link($text) {
	return ereg_replace("([a-zA-Z0-9]*@[a-zA-Z0-9\.]*\.[a-zA-Z]{2,4})", "<a href=\"mailto:\\0\">\\0</a>", $text);
}

function safesql($str){
	return mysql_escape_string($str);
}


if (!function_exists('array_walk_recursive'))
{
    function array_walk_recursive(&$input, $funcname, $userdata = "")
    {
        if (!is_callable($funcname))
        {
            return false;
        }
       
        if (!is_array($input))
        {
            return false;
        }
       
        foreach ($input AS $key => $value)
        {
            if (is_array($input[$key]))
            {
                array_walk_recursive($input[$key], $funcname, $userdata);
            }
            else
            {
                $saved_value = $value;
                if (!empty($userdata))
                {
                    $funcname($value, $key, $userdata);
                }
                else
                {
                    $funcname($value, $key);
                }
               
                if ($value != $saved_value)
                {
                    $input[$key] = $value;
                }
            }
        }
        return true;
    }
}

?>